<?php

namespace app\admin\controller;

use app\common\model\tpzs\Config;
use app\common\model\tpzs\Grouppos;
use app\common\model\tpzs\Position;
use app\common\model\tpzs\Union;
use ky\Jtt;
use YearDley\EasyTBK\Factory;
use think\Db;

class Tpzspos extends Botbase
{
    /**
     * @var Union
     */
    private $unionM;
    /**
     * @var Position
     */
    protected $model;
    /**
     * @var Grouppos
     */
    private $groupPosM;
    /**
     * @var Config
     */
    private $configM;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new Position();
        $this->unionM = new Union();
        $this->groupPosM = new Grouppos();
        $this->configM = new Config();
    }

    /**
     * 推广位
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        $union_id = input('union_id', 0);
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = ['admin_id' => $this->adminInfo['id'], 'union_id' => $union_id];
            !empty($post_data['search_key']) && $where['title|position_id'] = ['like', '%' . $post_data['search_key'] . '%'];
            $total = $this->model->total($where, true);
            if ($total) {
                $list = $this->model->getList(
                    [$post_data['page'], $post_data['limit']],
                    $where, [], true, true
                );
            } else {
                $list = [];
            }
            $this->success('success', '', ['total' => $total, 'list' => $list]);
        }
        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词搜索', 'placeholder' => '名称或推广位ID']
        ])
            ->setDataUrl(url('index', ['union_id' => $union_id]))
            ->addTopButton('addnew', ['title' => '添加推广位'])
            ->addTopButton('self', ['title' => '同步推广位', 'href' => url('syncPost'), 'data-ajax' => 1])
            ->addTableColumn(['title' => '序号', 'field' => 'id', 'type' => 'index','minWidth' => 50])
            ->addTableColumn(['title' => '推广位名称', 'field' => 'title', 'minWidth' => 100])
            ->addTableColumn(['title' => '推广位ID', 'field' => 'position_id', 'minWidth' => 80])
            ->addTableColumn(['title' => '类型', 'field' => 'type', 'type' => 'enum', 'options' => [1 => '接口添加', 2 => '联盟后台'], 'minWidth' => 80])
            ->addTableColumn(['title' => '站点类型', 'field' => 'jd_type', 'type' => 'enum', 'options' => [0 => '', 1 => '网站推广位', 2 => 'APP推广位', 3 => '导购媒体推广位', 4 => '聊天工具推广位'], 'minWidth' => 80])
            ->addTableColumn(['title' => '是否默认', 'field' => 'default', 'type' => 'enum', 'options' => [1 => '是', 0 => '否'], 'minWidth' => 50])
            ->addTableColumn(['title' => '操作', 'width' => 120, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('edit', ['title' => '关联群', 'href' => url('bindGroup', ['id' => '__data_id__']), 'class' => 'layui-btn layui-btn-xs']);

        return $builder->show();
    }

    /**
     * 绑定群
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function bindGroup(){
        if(request()->isPost()){
            $post_data = input('post.');
            $groups = explode(',', $post_data['groups']);
            foreach ($groups as $group_id){
                if($d = $this->groupPosM->getOneByMap(['bot_id' => $this->bot['id'], 'position_id' => $post_data['position_id'], 'group_id' => $group_id])){
                    $this->groupPosM->updateOne([
                        'id' => $d['id'],
                        'position_id' => $post_data['position_id'],
                        'bot_id' => $this->bot['id']
                    ]);
                }else{
                    $this->groupPosM->addOne([
                        'position_id' => $post_data['position_id'],
                        'group_id' => $group_id,
                        'bot_id' => $this->bot['id']
                    ]);
                }
            }
            $this->groupPosM->delByMap(['bot_id' => $this->bot['id'], 'position_id' => $post_data['position_id'], 'group_id' => ['notin', $groups]]);
            $this->success('操作成功');
        }
        $id = input('id');
        $data = $this->model->getOne($id);
        $data['positionid'] = $data['position_id'];
        $data['position_id'] = $id;
        if($gp = $this->groupPosM->getField(['group_id'], ['position_id' => $id, 'bot_id' => $this->bot['id']])){
            $data['groups'] = $gp;
        }else{
            $data['groups'] = [];
        }
        $groups = model('admin/botMember')->getField('id,nickname',['uin' => $this->bot['uin'], 'type' => \app\constants\Bot::GROUP]);
        //使用FormBuilder快速建立表单页面。
        $builder = new FormBuilder();
        $builder->setMetaTitle('关联群')  //设置页面标题
            ->setPostUrl(url('bindGroup')) //设置表单提交地址
            ->addFormItem('position_id', 'hidden', 'group id', 'group id')
            ->addFormItem('title', 'static', '推广位', $data['title']."(".$data['positionid'].")")
            ->addFormItem('groups', 'chosen_multi', '群聊', '群聊', $groups, 'required')
            ->setFormData($data);

        return $builder->show();
    }

    /**
     * 新增
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add()
    {
        $data['admin_id'] = $this->adminInfo['id'];
        $unionId = $this->unionM->getField(['id','title'], ['admin_id' => $this->adminInfo['id'], 'status' => 1]);
        $builder = new FormBuilder();
        $builder->setMetaTitle('新增推广位')  //设置页面标题
            ->setPostUrl(url('savePost')) //设置表单提交地址
            ->setTip("站点ID：如果站点类型不是选择聊天工具推广位，则站点ID必填")
            ->addFormItem('admin_id', 'hidden', 'adminid')
            ->addFormItem('union_id', 'select', '联盟id', '联盟id', $unionId, 'required')
            ->addFormItem('union_type', 'select', '推广位类型', '推广位类型', [3 => '私域推广位', 4 => '联盟后台推广位'], 'required')
            ->addFormItem('jd_type', 'select', '站点类型', '站点类型', Position::jdTypes(), 'required')
            ->addFormItem('title', 'text', '推广位名称', '推广位名称', [], 'required')
            ->addFormItem('siteid', 'text', '站点ID', '站点ID', [], '')
            ->setFormData($data);
        return $builder->show();
    }

    public function edit()
    {
        $id = input('id');
        $data = $this->model->getOne($id);
        if (!$data) {
            $this->error('id参数错误' . $id);
        }
        $builder = new FormBuilder();
        $builder->setMetaTitle('编辑推广位')  //设置页面标题
            ->setPostUrl(url('savePost')) //设置表单提交地址
            ->addFormItem('id', 'hidden', 'id', 'id')
            ->addFormItem('default', 'radio', '是否默认', '是否默认', [1 => '是', 0 => '否'], 'required')
            ->setFormData($data);
        return $builder->show();
    }

    public function savePost($jump_to = '', $data = [])
    {
        $post_data = input('post.');
        if (empty($post_data[$this->pk])) {
            $conf = $this->configM->getConf(['admin_id' => $this->bot['admin_id']]);
            //创建京东推广位
            $union = $this->unionM->getOne($post_data['union_id']);
            $param = [
                'unionid' => $union['unionid'],
                'key' => $union['app_key'],
                'unionType' => $post_data['union_type'],
                'type' => $post_data['jd_type'],
                'name' => $post_data['title'],
            ];
            if (!empty($post_data['siteid'])){
                $param['siteId'] = $post_data['siteid'];
            }

            $jtt = new Jtt(['appid' => $conf['jtt_appid'], 'appkey' => $conf['jtt_appkey']]);
            if(($res = $jtt->newPosition($param)) !== false){
                $post_data['position_id'] = $res['positionid'];
                $res = $this->model->addOne($post_data);
            } else {
                $this->error("创建推广位接口请求错误");
            }
        } else {
            if ($post_data['default']) {
                $this->model->updateByMap(['admin_id' => $this->adminInfo['id'], 'default' => 1], ['default' => 0]);
            }
            $res = $this->model->updateOne($post_data);
        }
        if ($res) {
            $this->success('数据保存成功', $jump_to);
        } else {
            $this->error('数据保存出错');
        }
    }

    /**
     * 同步推广位
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncPost()
    {
        $config = $this->configM->getConf(['admin_id' => $this->bot['admin_id']]);
        if (empty($config['jd_appkey']) || empty($config['jd_appsecret'])) {
            $this->error('请先配置京东开放平台参数');
        }
        $jd_appkey = trim($config['jd_appkey']);
        $jd_appsecret = trim($config['jd_appsecret']);
        $client = Factory::jingdong([
            'app_key' => $jd_appkey,
            'app_secret' => $jd_appsecret,
            'format' => 'json'
        ]);
        $request = new \YearDley\EasyTBK\JingDong\Request\JdUnionPositionQueryRequest();
        //获取用户账号列表
        $account_list = $this->unionM->getAll([
            'where' => ['admin_id' => $this->adminInfo['id'], 'status' => 1]
        ]);
        $insert_data = [];
        foreach ($account_list as $val) {
            $league_id = $val['unionid'];
            $app_key = $val['app_key'];
            $request->setUnionId($league_id);
            $request->setKey($app_key);
            $request->setUnionType(4);
            $request->setPageIndex(1);
            $request->setPageSize(100);
            $res = $client->execute($request);
            $result = json_decode($res['jd_union_open_position_query_response']['result'], true);
            if($result['code'] == 200){
                $data = $result['data']['result'];
                $total = $result['data']['total'];
                $total_page = ceil($total / 100);
                for ($page = 1; $page <= $total_page; $page++) {
                    $request->setUnionId($league_id);
                    $request->setKey($app_key);
                    $request->setUnionType(4);
                    $request->setPageIndex($page);
                    $request->setPageSize(100);
                    $res2 = $client->execute($request);
                    $result2 = json_decode($res2['jd_union_open_position_query_response']['result'], true);
                    $data2 = $result2['data']['result'];
                    foreach ($data2 as $val2) {
                        $position_id = $val2['id'];
                        $exist = $this->model->total(['position_id' => $position_id]);
                        if (empty($exist)) {
                            $insert_data[] = [
                                'title' => $val2['spaceName'],
                                'union_id' => $val['id'],
                                'position_id' => $position_id,
                                'type' => 2,
                                'admin_id' => $this->adminInfo['id'],
                                'jd_type' => $val2['type'],
                                'siteid' => $val2['siteId'],
                            ];
                        }
                    }
                }
            } else {
                $this->error('联盟id：'.$league_id.':'.$result['message']);
            }
        }
        if ($insert_data) {
            $this->model->addBatch($insert_data);
        }
        $this->success('同步完成');
    }
}
